import {
  ProCoreActionType,
  RequestData,
  stringify,
} from '@ant-design/pro-components';
import useFetchData from '@ant-design/pro-descriptions/es/useFetchData';
import SfwLoadingContainer, {
  SfwLoadingContainerProps,
} from '@sfkj/sfw-dc-ui/common/SfwLoadingContainer';
import React from 'react';

export type SfwRequestContainerProps = {
  /** Params 参数 params 改变的时候会触发 reload */
  params?: Record<string, any>;
  /** 网络请求报错 */
  onRequestError?: (e: Error) => void;
  /** 获取数据的方法 */
  request: (
    params: Record<string, any> | undefined,
  ) => Promise<RequestData<any>>;
  /** 一些简单的操作 */
  actionRef?: React.MutableRefObject<ProCoreActionType<any> | undefined>;
  loadingContainer?: SfwLoadingContainerProps;
  onDataSourceChange: (value: any['data'], action?: any) => void;
  onLoadingChange: (loading?: boolean, action?: any) => void;
} & Record<string, any>;

const SfwRequestContainer: React.FC<SfwRequestContainerProps> = (props) => {
  const {
    children,
    params,
    request,
    actionRef,
    loadingContainer,
    onDataSourceChange,
    onLoadingChange,
    ...rest
  } = props;

  const [error, setError] = React.useState<any>();

  const action = useFetchData<any>(
    async () =>
      request
        ? await request(params || {})
        : ({ data: {} } as RequestData<any>),
    {
      effects: [stringify(params)],
      onRequestError: (e) => {
        setError(e);
      },
      manual: !request,
      onLoadingChange: (loading) => {
        if (onLoadingChange) {
          onLoadingChange(loading, action);
        }
      },
      onDataSourceChange: (value) => {
        if (onDataSourceChange) {
          onDataSourceChange(value, action);
        }
      },
    },
  );
  const { loading, dataSource } = action;
  const queryResult = {
    loading,
    data: dataSource?.data,
    error: error,
  };

  React.useEffect(() => {
    if (actionRef) {
      actionRef.current = {
        reload: action.reload,
      };
    }
  }, [action, actionRef]);

  console.debug('[SFW] SfwRequestContainer', props, action, error);

  return (
    <SfwLoadingContainer
      queryResult={queryResult}
      errorView={{
        onRetry: async () => {
          setError(null);
          await action.reload();
        },
      }}
      {...loadingContainer}
      {...rest}
    >
      {children}
    </SfwLoadingContainer>
  );
};

export default SfwRequestContainer;
